﻿using System;
using System.Threading;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Data;

namespace SubscriberSheet
{
    public partial class MkvSheet : Form
    {
        public MkvSheet()
        {
            InitializeComponent();
        }

        static Ion.MarketView.Ifc.Application app = Ion.MarketView.Ifc.Application.Instance;
        readonly Thread _th = new Thread(Target);
        delegate void DictParameterDelegate(IDictionary<String, String> value);
        private readonly DataTable _dataTable = new DataTable("QUOTE");
        
        private void MkvSheet_Load(object sender, EventArgs e)
        {
            dataGridView1.DataSource = _dataTable;
            DataColumn colItem1 = new DataColumn("Name", Type.GetType("System.String"));
            _dataTable.Columns.Add(colItem1);
            DataColumn colItem2 = new DataColumn("Type", Type.GetType("System.String"));
            _dataTable.Columns.Add(colItem2);
            DataColumn colItem3 = new DataColumn("Value", Type.GetType("System.String"));
            _dataTable.Columns.Add(colItem3);

            var handler = new MkvEventHandler(this);
            app.PersistentSubscriptions = true;
            app.Initializing += handler.Initialize;
            app.NewService += handler.NewService;
            app.PasswordChange += handler.PasswordChange;
            app.RegisterIdle += handler.RegisteredIdle;
            app.Registered += handler.Registered;
            app.Started += handler.Started;
            app.Stopped += handler.Stopped;

            _th.Start();            
        }

        private static void Target()
        {
            app.Initialize();
        }


        private void MkvSheet_Closing(object sender, EventArgs e)
        {
            _th.Interrupt();
            app.Stop();            
        }

        public void UpdateTable(IDictionary<String, String> dict)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new DictParameterDelegate(UpdateTable), new Object[] { dict });
                return;
            }

            foreach (String _fldName in dict.Keys)
            {
                DataRow NewRow = _dataTable.NewRow();
                NewRow["Name"] = _fldName;
                NewRow["Type"] = dict[_fldName];
                NewRow["Value"] = "0.0";
                _dataTable.Rows.Add(NewRow);
            }
            _dataTable.AcceptChanges();
            dataGridView1.AllowUserToAddRows = false;
        }
    }
}
